import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class SecondTest {
    WebDriver driver = null;
    // 创造driver 便于后续每次使用
    void createDriver() {
        // 打开浏览器 使用驱动打开
        WebDriverManager.chromedriver().setup();
        // 增加浏览器配置
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        driver = new ChromeDriver(options);


        driver.get("https://www.baidu.com/");
    }

    void test01() throws InterruptedException {
        createDriver();
        //选择器
        //driver.findElement(By.cssSelector("#s-hotsearch-wrapper > div"));
        //driver.findElement(By.xpath("//*[@id=\"s-hotsearch-wrapper\"]/div"));
        Thread.sleep(2000);
        // 获取 热搜关键词
        List<WebElement> ll = driver.findElements(By.cssSelector("#hotsearch-content-wrapper > li > a > span.title-content-title"));
        for(int i = 0;i < 6 ;i ++)
        {
            //获取元素对应的文本
            System.out.println(ll.get(i).getText());
        }
        driver.quit();

    }

    // 屏幕截图
    void getScreenShot(String str) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmss");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        // ./src/pic/2024-9-2/SecondTest-xxxxxx.png
        String filename = "./src/pic/" + dirTime + "/" + str + "-" + fileTime + ".png";
        System.out.println("filename:" + filename);
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        // srcFile 放到指定位置
        FileUtils.copyFile(srcFile, new File(filename));
    }

    // 窗口切换 截图测试
    void test02() throws IOException, InterruptedException {
        createDriver();
        getScreenShot(getClass().getName());


        driver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();
        Thread.sleep(1000);
        getScreenShot(getClass().getName());
        // 获取当前窗口句柄
        String curHandle = driver.getWindowHandle();
        // 获取所有窗口的句柄
        Set<String> allHandles = driver.getWindowHandles();

        // 切换窗口
        for (String handle : allHandles) {
            if (handle != curHandle) {
                driver.switchTo().window(handle);
            }
        }
        driver.findElement(By.cssSelector("#pane-news > div > ul > li.hdline0 > strong > a")).click();
        Thread.sleep(3000);
        getScreenShot(getClass().getName());
        driver.quit();

    }

}
